package com.guosen.zebra.framework.starter.ngx.internal.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.guosen.zebra.framework.starter.ngx.exception.NgxException;
import com.guosen.zebra.framework.starter.ngx.model.DownloadParameter;
import com.guosen.zebra.framework.starter.ngx.model.DownloadResult;
import com.guosen.zebra.framework.starter.ngx.model.InvokeContext;
import com.guosen.zebra.framework.starter.ngx.util.UrlEncodeDecoder;

import java.util.HashMap;
import java.util.Map;

public class UniNgxDownload {

    /**
     * 下载文件路径
     */
    private static final String DOWNLOAD_PATH = "/UniExServices/restfulapi/%s%s";

    public DownloadResult execute(DownloadParameter downloadParameter, InvokeContext invokeContext) throws NgxException {
        String urlEncodeAccount = UrlEncodeDecoder.encode(invokeContext.getAccount());
        String urlEncodePath = UniNgxUtil.urlEncodePath(downloadParameter.getPath());
        String url = invokeContext.getAddress() + String.format(DOWNLOAD_PATH, urlEncodeAccount, urlEncodePath);

        Map<String, String> parameters = buildParameters(downloadParameter);
        Map<String, String> headers = UniNgxUtil.buildHeaders(invokeContext);

        Object result = UniNgxRestfulClient.downloadFile(url, headers, parameters);
        if (result instanceof JsonNode) {
            UniNgxUtil.raiseExceptionIfExist((JsonNode)result);
        }

        DownloadResult downloadResult = new DownloadResult();
        downloadResult.setFileContent((byte[])result);

        return downloadResult;
    }

    private Map<String, String> buildParameters(DownloadParameter downloadParameter) {
        Map<String, String> parameters = new HashMap<>();
        UniNgxUtil.addParameter(parameters, "method", "download");
        UniNgxUtil.addParameter(parameters, "location", downloadParameter.getLocation());
        UniNgxUtil.addParameter(parameters, "is_dir", downloadParameter.getIsDir());

        return parameters;
    }
}
